<template>
  <!-- 导航栏 -->
  <van-nav-bar
    title="确认订单"
    left-text="返回"
    left-arrow
    fixed
    placeholder
    z-index="1000"
    @click-left="back"
  />

  <!-- 收货地址 -->
  <van-contact-card v-if="address" type="edit" :name="`${address.name} ${address.region_text}`" :tel="address.tel" @click="AddressSelect" />
  <van-contact-card v-else type="add" @click="AddressAdd" />


  <!-- 商品卡片 -->
  <van-card
    v-for="(item, key) in list"
    :thumb="item.product.thumbs_text"
    :num="item.nums"
    @click-thumb="toProductInfo(item.proid)"
  >
    <template #title>
      <div class="title">{{item.product.name}}</div>
    </template>

    <!-- 商品规格 -->
    <template #desc v-if="item.attrs">
      <div class="TagGroup">
        <van-tag v-for="(attr,index) in item.attrs" :key="index" class="tag" type="primary">{{attr.value}}</van-tag>
      </div>
    </template>
    <template #desc v-else>
      <div class="TagGroup">
        <van-tag class="tag" type="danger">无规格数据</van-tag>
      </div>
    </template>

    <template #tags>
      <div class="price">单价：￥{{item.price}}</div>
    </template>

    <template #price>
      <div class="price">合计：￥{{item.total}}</div>
    </template>
  </van-card>


  <!-- 支付方式 -->
  <van-cell title="支付方式" :value="PayActive.text" is-link @click="PayShow = true"></van-cell>

  <!-- 优惠券 -->
  <van-coupon-cell
    :coupons="CouponList"
    :chosen-coupon="CouponActive"
    @click="CouponShow = true"
  />

  <!-- 订单备注 -->
  <van-field
    v-model="remark"
    rows="2"
    autosize
    label="订单备注"
    type="textarea"
    maxlength="120"
    placeholder="请输入订单备注"
    show-word-limit
  />

  <!-- 优惠券选择器 -->
  <van-popup v-model:show="CouponShow" position="bottom">
    <van-coupon-list
      :coupons="CouponList"
      :chosen-coupon="CouponActive"
      :exchange-button-disabled="true"
      :show-exchange-bar="false"
      @change="CouponSelect"
    />
  </van-popup>

  <!-- 支付方式的选择器 -->
  <van-popup v-model:show="PayShow" position="bottom">
    <van-picker
      title="选择支付方式"
      :columns="PayList"
      @cancel="PayShow = false"
      @confirm="PayConfirm"
    />
  </van-popup>

  <!-- 提交动作栏 -->
  <van-submit-bar text-align="left" :price="total" button-text="确认支付" @submit="submit" />
</template>

<script setup>

  const {proxy} = getCurrentInstance()
  let business = proxy.$business
  //获取下单的购物车id
  let cartids = proxy.$route.query.cartids ? proxy.$route.query.cartids : '0'
  let list = ref([]) //购物车数据
  let address = ref(null) //收货地址
  let remark = ref('') //订单备注
  //支付方式
  let PayShow = ref(false)
  let PayActive = ref({text: '余额支付', value: 'money'})
  let PayList = ref([
    {text: '余额支付', value: 'money'},
    {text: '微信支付', value: 'wx'},
    {text: '支付宝', value: 'zfb'},
  ])

  // 优惠券
  let CouponList = ref([]);
  let CouponShow = ref(false);
  let CouponActive = ref(-1);

  onMounted(() => {
    CartInfo()
    AddressInfo()
    CouponInfo()
  })


  // 总价合计
  let originalTotal = ref(0)
  const total = computed(() => {
    var total = 0
    
    list.value.map((item) => total += parseFloat(item.total))

    originalTotal = total*100
    
    // 使用优惠券
    if(CouponActive.value != -1)
    {
      var rate = CouponList.value[CouponActive.value].rate

      total = (total * rate).toFixed(2)
    }

    return parseFloat(total*100)
  })

  //确认支付方式
  const PayConfirm = async ({selectedOptions}) => 
  {
    PayShow.value = false
    PayActive.value = selectedOptions[0]
    console.log(selectedOptions)
  }

  //购物车数据
  const CartInfo = async () =>
  {
    //组装数据
    var params = {
      busid: proxy.$business.value.id,
      cartids
    }

    var result = await proxy.$POST({
      url: '/cart/index',
      params
    })

    if(result.code == 0)
    {
      proxy.$fail(result.msg)
      return false
    }

    result.data.map(item => item.attrs = JSON.parse(item.attrs))

    list.value = result.data
  }

  //收货地址
  const AddressInfo = async () =>
  {

    //先从缓存当中获取，如果有就直接赋值，没有在去通过接口请求
    if(proxy.$address.value)
    {
      address.value = proxy.$address.value
    }else
    {
      var result = await proxy.$POST({
        url: '/address/selected',
        params: {busid: business.value.id}
      })

      if(result.code == 0) return false

      address.value = result.data
    }
  }

  //返回优惠券的方法
  const CouponInfo = async () =>
  {
    var result = await proxy.$POST({
      url: '/business/coupon',
      params: {busid: business.value.id}
    })
  
    if(result.code && result.data.length > 0)
    {
      var coupons = []

      for(var item of result.data)
      {
        coupons.push({
          id: item.id,
          condition: item.coupon.status_text,
          rate: item.coupon.rate,
          name: item.coupon.title,
          startAt: item.coupon.createtime,
          endAt: item.coupon.endtime,
          valueDesc: `${item.coupon.rate*100}`,
          unitDesc: '折',
        })
      }

      CouponList.value = coupons
    }
  }


  //确认选择优惠券
  const CouponSelect = async (index) =>
  {
    CouponShow.value = false
    CouponActive.value = index

    //使用优惠券
    if(index != -1)
    {
      //计算
      var Total = originalTotal / 100
      var rate = CouponList.value[index].rate
      var price = Total * rate
      var CouponPrice = Total - price
      CouponPrice = parseFloat(CouponPrice*100).toFixed(2)
      CouponList.value[index].value = CouponPrice
    }
  }

  //跳转收货地址的列表界面
  const AddressSelect = () => 
  {
    proxy.$router.push({path: '/address', query: {action: 'select'}})
  }

  //跳转收货地址添加界面
  const AddressAdd = () => proxy.$router.push('/address/add')

  //返回上一页
  const back = () => proxy.$router.go(-1)


  //提交表单
  const submit = async () =>
  {
    //组装数据
    var params = {
      busid: business.value.id,
      addrid: address.value.id,
      cartids: cartids,
      remark: remark.value,
      pay:PayActive.value.value
    }
    //判断是否有使用优惠券
    if(CouponActive.value != -1)
    {
      params.couponid = CouponList.value[CouponActive.value].id
    }

    //发送接口请求
    var result = await proxy.$POST({url: '/order/add', params})

    if(result.code == 0)
    {
      proxy.$fail(result.msg)
      return false
    }

    if(params.pay == 'money')
    { 
      //这里是余额支付,因此控制器中传来的result.url 是order/info
      proxy.$success({
        message: result.msg,
        onClose: () => proxy.$router.push({path: result.url, query: {orderid: result.data.orderid}})
      })
    }else
    {
      // 第三方支付 result.url 是跳转收银台 cart/cashier
      proxy.$success({
        message: result.msg,
        onClose: () => proxy.$router.push({path: result.url, query: {payid: result.data.id}})
      })
    }

  }
</script>

<style scoped>
  :deep(.cart) {
    display: flex;
    width: 100%;
  }
  ::v-deep .van-swipe-cell {
    width: 100%;
  }
  .delete-button {
    height: 100%;
  }


  .van-card{
    background-color:#fff;
  }

  .title{
    font-size:16px;
    font-weight: bold;
    margin-bottom:5px;
  }

  .TagGroup{
    margin-bottom:5px;
  }

  .tag{
    margin-right:5px;
  }

  .price{
    font-size:14px;
    font-weight: bold;
  }
</style>